<template>
  <div>
    <el-row>
      <el-col :span="4">
        <div class="tree">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>
          <el-tree @node-click="handlerClick" class="filter-tree" :data="EngData" :props="defaultProps"
            :filter-node-method="filterNode" ref="tree">
          </el-tree>
        </div>
      </el-col>

      <el-col :span="20">
        <!-- 只有当 device_id 有值（即用户点击了设备）时，
          才显示数据表格区域。否则显示 "请点击设备查看数据 -->
        <div v-if="params.device_id" class="table">
          <!-- 搜索表单 -->
          <el-form :inline="true" :model="form">
            <el-form-item>
              <div class="block">
                <span class="demonstration"></span>
                <el-date-picker v-model="form.date" type="month" placeholder="选择月" value-format="yyyy-MM">
                </el-date-picker>
              </div>
            </el-form-item>
            <el-form-item>
              <!--  搜索按钮，点击触发 toSearch 方法 -->
              <el-button type="primary" @click="toSearch" icon="el-icon-search">搜索</el-button>
            </el-form-item>
          </el-form>

          <!-- 表格 -->
          <el-table :data="monitorData" style="width: 100%" :row-class-name="tableRowClassName">
            <!-- 日期列 -->
            <el-table-column prop="date" label="日期" width="180" align="center">
              <!-- 作用域插槽自定义单元格内容 -->
              <template v-slot="scope">
                <div>
                  {{ scope.row.date }}
                </div>
              </template>
            </el-table-column>
            <!-- 其他数据列，prop绑定数据对象的属性名，label是表头名 -->
            <el-table-column prop="tsp" label="tsp" width="180" align="center">
            </el-table-column>
            <el-table-column prop="pm10" label="pm10" align="center">
            </el-table-column>
            <el-table-column prop="pm25" label="pm2.5" align="center">
            </el-table-column>
            <el-table-column prop="temperature" label="温度" align="center">
            </el-table-column>
            <el-table-column prop="humidity" label="湿度" align="center">
            </el-table-column>
            <el-table-column prop="wind_direction" label="风向" align="center">
            </el-table-column>
            <el-table-column prop="wind_speed" label="风速" align="center">
            </el-table-column>
          </el-table>

          <!-- 分页开始 -->
          <div class="pagination-container" style="margin-top: 20px; text-align: right;">
            <!-- layout分页布局：上一页、页码、下一页
              total总数据条数
              page-size每页显示条数 -->
            <el-pagination  layout="prev, pager, next" :total="total" :page-size="pageSize"
              :current-page="currentPage" @current-change="pageChange">
            </el-pagination>
          </div>
          <!-- 分页结束 -->
        </div>
        <div v-else style="line-height: 50px;color: cornflowerblue;font-size: 20px;text-align: center;">
          请点击设备查看数据
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { get } from '@/utils/request';
export default {
  data() {
    return {
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 用一个变量存储当前页数据
      monitorData: [],
      form: {
        date: ''
      },
      EngData: [],
      currentMonth: '',
      params: {
        device_id: 0,
        engineer_id: 0
      },
      test: [],
      // 分页参数
      pageSize: 5,
      currentPage: 1,
      total: 0
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    handlerClick(val, node) {
      if (!val.children) {
        this.params.device_id = val.id;
        this.params.engineer_id = val.engineer_id;
        if (this.form.date) {
          this.getMonitor();
        }
      }
    },
    toSearch() {
      if (!this.form.date) {
        this.$message.warning('请选择要查询的月份');
        return;
      }
      //每次搜索都重置到第1页
      this.currentPage = 1;
      this.getMonitor();
    },
    //页码切换事件
    pageChange(newPage) {
      this.currentPage = newPage;
      //直接调用 getMonitor 获取新一页数据
      this.getMonitor();
    },
    // 封装方法获取监测月报数据
    async getMonitor() {
      let temp = {
        ...this.params,
        date: this.form.date
      };
      let res = await get('/dashboard/queryMouthData', temp);
      console.log(res, '月报数据-----------');
      const metricTypes = ['tsp', 'pm10', 'pm25', 'noise', 'temperature', 'humidity', 'wind_speed', 'wind_direction'];
      this.test = {};
      metricTypes.forEach(type => {
        this.test[type] = res.data.filter(item => item.type === type);
      });
      // 先将所有数据转换出来
      const allData = this.test.tsp.map((tspItem, index) => {
        const row = { date: tspItem.date, tsp: tspItem.value + '' };
        metricTypes.slice(1).forEach(type => {
          row[type] = this.test[type][index]?.value + '';
        });
        return row;
      });
      // 更新总数据条数
      this.total = allData.length;
      // 根据当前页码和页大小，计算并直接赋值给 monitorData
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.monitorData = allData.slice(startIndex, endIndex);
    },
    async getEngDevData() {
      let res = await get('/engineer/findEngineerDeviceTree');
      console.log(res, '888888');
      this.EngData = res.data;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'warning-row';
      } else {
        return 'success-row';
      }
    }
  },
  created() {
    this.getEngDevData();
  }
}
</script>
<style lang="scss" scoped>
.tree {
  height: calc(100vh - 60px);
  padding-right: 20px;
  border-right: 1px solid #ececec;
  margin-right: 10px;
}
::v-deep .el-table .warning-row {
  background: rgb(204, 248, 204);
}
::v-deep .el-table .success-row {
  background: #f9feea;
}
::v-deep .el-form-item__label {
  font-weight: 500;
}
</style>